/*
 * @Author: modefy
 * @Date: 2021-12-06 10:13:57
 * @LastEditors: modefy
 * @LastEditTime: 2023-05-10 16:20:11
 * @Description: Description
 */
import Router from '@/router'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

console.log(import.meta.env.VITE_BASE_API_MODEFY, '地址')

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API_MODEFY, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor （请求拦截）
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['token'] = token
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor （响应拦截）
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    const res = response.data
    if (res.code !== 200) {
      if(res.code === '0') {
        // token失效
        localStorage.removeItem('token')
        Router.replace('/')
      }
      return Promise.reject(res.msg)
    } else {
      return Promise.resolve(res)
    }
  },
  (error) => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
